package com.itheima.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2023/5/4 9:27
 */
@Slf4j
@RestController
@RequestMapping
public class DemoController {
    @Value("${server.port}")
    private String port;

    private AtomicInteger count = new AtomicInteger(0);

    @RequestMapping("/hello")
    public String hello(){
        int count = this.count.incrementAndGet();
        log.info("浏览器第{}次访问~", this.count);
        return "Hello World！My publish port is : " + port + ", count : " + count + " 通过原生shell脚本+docker方式发布！";
    }

    @RequestMapping("/cpu")
    public void cpu(){
        System.out.println("高CPU演示程序启动，进程PID: " + ProcessHandle.current().pid());

        // 创建多个线程来消耗CPU
        for (int i = 0; i < Runtime.getRuntime().availableProcessors(); i++) {
            new Thread(() -> {
                while (true) {
                    // 模拟高CPU计算：计算斐波那契数列
                    fibonacci(40);
                }
            }, "High-CPU-Thread-" + i).start();
        }
    }

    // 递归计算斐波那契数列（高CPU消耗）
    private static long fibonacci(int n) {
        if (n <= 1) {return n;};
        return fibonacci(n - 1) + fibonacci(n - 2);
    }


    private static final List<byte[]> memoryHog = new ArrayList<>();
    @RequestMapping("/memory")
    public void memory() throws InterruptedException {
        System.out.println("高内存演示程序启动，进程PID: " + ProcessHandle.current().pid());

        // 每秒钟分配100MB内存
        int chunkSize = 100 * 1024 * 1024; // 100MB

        for (int i = 0; i < 20; i++) {
            System.out.println("分配第 " + (i + 1) + " 个100MB内存块...");
            byte[] memoryChunk = new byte[chunkSize];
            // 填充数据防止被优化掉
            for (int j = 0; j < memoryChunk.length; j += 4096) {
                memoryChunk[j] = 1;
            }
            memoryHog.add(memoryChunk);

            TimeUnit.SECONDS.sleep(1);
        }

        System.out.println("内存分配完成，程序将保持运行状态...");
        // 保持程序运行以便观察
        TimeUnit.HOURS.sleep(1);
    }
}
